package com.gitee.wsl.net.ssdp.device

import com.gitee.wsl.logger.Logger
import com.gitee.wsl.logger.debug
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import com.gitee.wsl.net.ssdp.description.model.DeviceManifest
import kotlin.coroutines.CoroutineContext

class DeviceManager (
    val addDeviceFlow: Flow<DeviceManifest>,
    val removeDeviceFlow: Flow<String>,
    override val coroutineContext: CoroutineContext = Dispatchers.IO + SupervisorJob(),
):  CoroutineScope{
    private val devices = mutableMapOf<String, DeviceManifest>()

    init {
        launch { addDeviceFlow.collect(::addDevice) }
        launch { removeDeviceFlow.collect(::removeDevice) }
    }

    fun removeDevice(usn: String) {
        Logger.debug("Removing device with USN: $usn")
        devices.remove(usn)
    }

    fun addDevice(device: DeviceManifest) {
        Logger.debug("Adding device: $device", )
        devices[device.usn] = device
    }
}